﻿using System;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using Emgu.CV;
using Emgu.CV.CvEnum;
using Emgu.CV.Structure;

namespace ImageProcess
{
    public class Gdi32
    {
        [DllImport("gdi32.dll")]
        public static extern bool BitBlt(IntPtr hObject, int nXDest, int nYDest, int nWidth, int nHeight, IntPtr hObjectSource, int nXSrc, int nYSrc, int dwRop);
        [DllImport("gdi32.dll")]
        public static extern IntPtr CreateCompatibleBitmap(IntPtr hDC, int nWidth, int nHeight);
        [DllImport("gdi32.dll")]
        public static extern IntPtr CreateCompatibleDC(IntPtr hDC);
        [DllImport("gdi32.dll")]
        public static extern bool DeleteDC(IntPtr hDC);
        [DllImport("gdi32.dll")]
        public static extern bool DeleteObject(IntPtr hObject);
        [DllImport("gdi32.dll")]
        public static extern IntPtr SelectObject(IntPtr hDC, IntPtr hObject);
    }

    public static class User32
    {
        [DllImport("user32.dll")]
        public static extern IntPtr GetDesktopWindow();
        [DllImport("user32.dll")]
        public static extern IntPtr GetWindowDC(IntPtr hWnd);
        [DllImport("user32.dll")]
        public static extern IntPtr GetWindowRect(IntPtr hWnd, ref RECT rect);
        [DllImport("user32.dll")]
        public static extern IntPtr ReleaseDC(IntPtr hWnd, IntPtr hDC);
    }
    [StructLayout(LayoutKind.Sequential)]
    public struct RECT
    {
        public int left;
        public int top;
        public int right;
        public int bottom;
    }
    

    public static class Utilities
    {
        public const int SRCCOPY = 13369376;

        public static Image CaptureScreen()
        {
            return CaptureWindow(User32.GetDesktopWindow());
        }

        public static Image CaptureWindow(IntPtr handle)
        {

            IntPtr hdcSrc = User32.GetWindowDC(handle);

            RECT windowRect = new RECT();
            User32.GetWindowRect(handle, ref windowRect);

            int width = windowRect.right - windowRect.left;
            int height = windowRect.bottom - windowRect.top;

            IntPtr hdcDest = Gdi32.CreateCompatibleDC(hdcSrc);
            IntPtr hBitmap = Gdi32.CreateCompatibleBitmap(hdcSrc, width, height);

            IntPtr hOld = Gdi32.SelectObject(hdcDest, hBitmap);
            Gdi32.BitBlt(hdcDest, 0, 0, width, height, hdcSrc, 0, 0, SRCCOPY);
            Gdi32.SelectObject(hdcDest, hOld);
            Gdi32.DeleteDC(hdcDest);
            User32.ReleaseDC(handle, hdcSrc);

            Image image = Image.FromHbitmap(hBitmap);
            Gdi32.DeleteObject(hBitmap);

            return image;
        }


        //模板匹配
        public static void ImageMatch(Bitmap TemplateImage, Bitmap OrgImage, out Point result, out bool IsFound,
            [Optional, DefaultParameterValue(1d)] double scale,
            [Optional, DefaultParameterValue("Gray")] string colorSpace)

        {
            //输入图像
            Image<Bgr, Byte> imageInput = new Image<Bgr, byte>(OrgImage);
            //模板图像
            Image<Bgr, Byte> imageTemplate = new Image<Bgr, byte>(TemplateImage);
            //缩放因子，更小的图像可以提高处理速度
            //double.TryParse(scale1, out scale);
            if (scale != 1d)
            {
                imageInput = imageInput.Resize(scale, INTER.CV_INTER_LINEAR);
                imageTemplate = imageTemplate.Resize(scale, INTER.CV_INTER_LINEAR);
            }
            //色彩空间
            //string colorSpace = (string)cmbColorSpace.SelectedItem;
            IImage imageInput2, imageTemplate2;
            if (colorSpace == "Gray")
            {
                imageInput2 = imageInput.Convert<Gray, Byte>();
                imageTemplate2 = imageTemplate.Convert<Gray, Byte>();
            }
            else if (colorSpace == "HSV")
            {
                imageInput2 = imageInput.Convert<Hsv, Byte>();
                imageTemplate2 = imageTemplate.Convert<Hsv, Byte>();
            }
            else
            {
                imageInput2 = imageInput.Copy();
                imageTemplate2 = imageTemplate.Copy();
            }
            //匹配方式数组
            TM_TYPE[] tmTypes = new TM_TYPE[]
            {
                TM_TYPE.CV_TM_SQDIFF, TM_TYPE.CV_TM_SQDIFF_NORMED, TM_TYPE.CV_TM_CCORR, TM_TYPE.CV_TM_CCORR_NORMED,
                TM_TYPE.CV_TM_CCOEFF, TM_TYPE.CV_TM_CCOEFF_NORMED
            };
            //输出图像（匹配结果）
            Image<Gray, Single>[] imageResults = new Image<Gray, float>[tmTypes.Length];
            //依次执行每种匹配，并归一化结果
            int i = 0;
            double totalTime = 0d; //总共用时
            double time; //每种匹配的用时
            //Stopwatch sw = new Stopwatch();
            //result = null;
            //result += string.Format("开始执行匹配（色彩空间：{0}，缩放因子：{1}）/r/n", colorSpace, scale);

            //sw.Start();
            //模板匹配（注意：因为接口IImage中没有名为MatchTemplate的定义，所以需要进行强制转换）
            //Image<Gray, Single> imageResult = imageInput2.MatchTemplate(imageTemplate2, tmType);
            Image<Gray, Single> imageResult;
            if (colorSpace == "Gray")
                imageResult = ((Image<Gray, Byte>) imageInput2).MatchTemplate((Image<Gray, Byte>) imageTemplate2,
                    TM_TYPE.CV_TM_SQDIFF);
            else if (colorSpace == "HSV")
                imageResult = ((Image<Hsv, Byte>) imageInput2).MatchTemplate((Image<Hsv, Byte>) imageTemplate2,
                    TM_TYPE.CV_TM_SQDIFF);
            else
                imageResult = ((Image<Bgr, Byte>) imageInput2).MatchTemplate((Image<Bgr, Byte>) imageTemplate2,
                    TM_TYPE.CV_TM_SQDIFF);
            //sw.Stop();
            //time = sw.Elapsed.TotalMilliseconds;
            //totalTime += time;
            //sw.Reset();
            //归一化结果
            CvInvoke.cvNormalize(imageResult.Ptr, imageResult.Ptr, 1d, 0d, NORM_TYPE.CV_MINMAX, IntPtr.Zero);
            //找到最匹配的点，以及该点的值
            double bestValue;
            Point bestPoint;
            FindBestMatchPointAndValue(imageResult, TM_TYPE.CV_TM_SQDIFF, out bestValue, out bestPoint);
            IsFound = !(bestValue < 0);
            result = bestPoint;
            ////在最匹配的点附近画一个跟模板一样大的矩形
            //Rectangle rect = new Rectangle(new Point(bestPoint.X - imageTemplate.Size.Width / 2, bestPoint.Y - imageTemplate.Size.Height / 2), imageTemplate.Size);
            //imageResult.Draw(rect, new Gray(bestValue), 2);
            ////保存结果图像到数组
            //imageResults[i] = imageResult;
            //i++;
            ////显示结果
            //result += string.Format("匹配方式：{0:G}，用时：{1:F05}毫秒，最匹配的点：({2},{3})，最匹配的值：{4}/r/n", TM_TYPE.CV_TM_SQDIFF, time, bestPoint.X, bestPoint.Y, bestValue);

            //result += string.Format("匹配结束，共用时：{0:F05}毫秒/r/n", totalTime);
            //显示结果图像
            //pbResultSqdiff.Image = ImageConverter.ImageSingleToBitmap<Gray>(imageResults[0]);
            //pbResultSqdiffNormalized.Image = ImageConverter.ImageSingleToBitmap<Gray>(imageResults[1]);
            //pbResultCcorr.Image = ImageConverter.ImageSingleToBitmap<Gray>(imageResults[2]);
            //pbResultCcorrNormalized.Image = ImageConverter.ImageSingleToBitmap<Gray>(imageResults[3]);
            //pbResultCcoeff.Image = ImageConverter.ImageSingleToBitmap<Gray>(imageResults[4]);
            //pbResultCcoeffNormalized.Image = ImageConverter.ImageSingleToBitmap<Gray>(imageResults[5]);
            //释放资源
            imageInput.Dispose();
            imageTemplate.Dispose();
            imageInput2.Dispose();
            imageTemplate2.Dispose();
            //foreach (Image<Gray, Single> imageResult in imageResults)
            imageResult.Dispose();
        }

        //找到最匹配的点，以及该点的值
        private static void FindBestMatchPointAndValue(Image<Gray, Single> image, TM_TYPE tmType, out double bestValue, out Point bestPoint)
        {
            bestValue = 0d;
            bestPoint = new Point(0, 0);
            double[] minValues, maxValues;
            Point[] minLocations, maxLocations;
            image.MinMax(out minValues, out maxValues, out minLocations, out maxLocations);
            //对于平方差匹配和归一化平方差匹配，最小值表示最好的匹配；其他情况下，最大值表示最好的匹配
            if (tmType == TM_TYPE.CV_TM_SQDIFF || tmType == TM_TYPE.CV_TM_SQDIFF_NORMED)
            {
                bestValue = minValues[0];
                bestPoint = minLocations[0];
            }
            else
            {
                bestValue = maxValues[0];
                bestPoint = maxLocations[0];
            }
        }
        /// <summary>
        /// 将任意浮点型图像转换成Byte图像；
        /// 本转换函数对浮点型图像的具体像素值没有要求，自动将值缩放到0～255之间。
        /// </summary>
        /// <typeparam name="TColor">图像的色彩空间</typeparam>
        /// <param name="source">浮点型图像</param>
        /// <returns>返回Byte型图像</returns>
        public static Image<TColor, Byte> ImageSingleToByte<TColor>(Image<TColor, Single> source)
            where TColor : struct, IColor
        {
            Image<TColor, Byte> dest = new Image<TColor, Byte>(source.Size);
            //得到源图像的最小和最大值
            double[] minVal, maxVal;
            Point[] minLoc, maxLoc;
            source.MinMax(out minVal, out maxVal, out minLoc, out maxLoc);
            double min = minVal[0];
            double max = maxVal[0];
            for (int i = 1; i < minVal.Length; i++)
            {
                min = Math.Min(min, minVal[i]);
                max = Math.Max(max, maxVal[i]);
            }
            //得到缩放比率和偏移量
            double scale = 1.0, shift = 0.0;
            scale = (max == min) ? 0.0 : 255.0 / (max - min);
            shift = (scale == 0) ? min : -min * scale;
            //缩放图像，并浮点图像缩放到256级的灰度
            CvInvoke.cvConvertScaleAbs(source.Ptr, dest.Ptr, scale, shift);
            return dest;
        }

        /// <summary>
        /// 将任意浮点型图像转换成每通道8位的Bitmap；
        /// 本转换函数对浮点型图像的具体像素值没有要求，自动将值缩放到0～255之间。
        /// </summary>
        /// <typeparam name="TColor">图像的色彩空间</typeparam>
        /// <param name="source">浮点型图像</param>
        /// <returns>返回每通道8位的Bitmap</returns>
        public static Bitmap ImageSingleToBitmap<TColor>(Image<TColor, Single> source)
            where TColor : struct, IColor
        {
            Image<TColor, Byte> dest = ImageSingleToByte<TColor>(source);
            Bitmap bitmap = dest.Bitmap;
            dest.Dispose();
            return bitmap;
        }
    }
}

//using System;
//using System.Collections.Generic;
//using System.Diagnostics;
//using System.Drawing;
//using System.Linq;
//using System.Text;
//using System.Threading.Tasks;
//using Emgu.CV;
//using Emgu.CV.CvEnum;
//using Emgu.CV.Structure;

//namespace yt
//{
//    class ImageProcess
//    {
//        //模板匹配
//        private void btnCalc_Click(object sender, EventArgs e)
//        {
//            //输入图像
//            Image<Bgr, Byte> imageInput = new Image<Bgr, byte>((Bitmap)pbInput.Image);
//            //模板图像
//            Image<Bgr, Byte> imageTemplate = new Image<Bgr, byte>((Bitmap)pbTemplate.Image);
//            //缩放因子，更小的图像可以提高处理速度
//            double scale = 1d;
//            double.TryParse(txtScale.Text, out scale);
//            if (scale != 1d)
//            {
//                imageInput = imageInput.Resize(scale, INTER.CV_INTER_LINEAR);
//                imageTemplate = imageTemplate.Resize(scale, INTER.CV_INTER_LINEAR);
//            }
//            //色彩空间
//            string colorSpace = (string)cmbColorSpace.SelectedItem;
//            IImage imageInput2, imageTemplate2;
//            if (colorSpace == "Gray")
//            {
//                imageInput2 = imageInput.Convert<Gray, Byte>();
//                imageTemplate2 = imageTemplate.Convert<Gray, Byte>();
//            }
//            else if (colorSpace == "HSV")
//            {
//                imageInput2 = imageInput.Convert<Hsv, Byte>();
//                imageTemplate2 = imageTemplate.Convert<Hsv, Byte>();
//            }
//            else
//            {
//                imageInput2 = imageInput.Copy();
//                imageTemplate2 = imageTemplate.Copy();
//            }
//            //匹配方式数组
//            TM_TYPE[] tmTypes = new TM_TYPE[] { TM_TYPE.CV_TM_SQDIFF, TM_TYPE.CV_TM_SQDIFF_NORMED, TM_TYPE.CV_TM_CCORR, TM_TYPE.CV_TM_CCORR_NORMED, TM_TYPE.CV_TM_CCOEFF, TM_TYPE.CV_TM_CCOEFF_NORMED };
//            //输出图像（匹配结果）
//            Image<Gray, Single>[] imageResults = new Image<Gray, float>[tmTypes.Length];
//            //依次执行每种匹配，并归一化结果
//            int i = 0;
//            double totalTime = 0d;  //总共用时
//            double time;            //每种匹配的用时
//            Stopwatch sw = new Stopwatch();
//            txtResult.Text += string.Format("开始执行匹配（色彩空间：{0}，缩放因子：{1}）/r/n", colorSpace, scale);
//            foreach (TM_TYPE tmType in tmTypes)
//            {
//                sw.Start();
//                //模板匹配（注意：因为接口IImage中没有名为MatchTemplate的定义，所以需要进行强制转换）
//                //Image<Gray, Single> imageResult = imageInput2.MatchTemplate(imageTemplate2, tmType);
//                Image<Gray, Single> imageResult;
//                if (colorSpace == "Gray")
//                    imageResult = ((Image<Gray, Byte>)imageInput2).MatchTemplate((Image<Gray, Byte>)imageTemplate2, tmType);
//                else if (colorSpace == "HSV")
//                    imageResult = ((Image<Hsv, Byte>)imageInput2).MatchTemplate((Image<Hsv, Byte>)imageTemplate2, tmType);
//                else
//                    imageResult = ((Image<Bgr, Byte>)imageInput2).MatchTemplate((Image<Bgr, Byte>)imageTemplate2, tmType);
//                sw.Stop();
//                time = sw.Elapsed.TotalMilliseconds;
//                totalTime += time;
//                sw.Reset();
//                //归一化结果
//                CvInvoke.cvNormalize(imageResult.Ptr, imageResult.Ptr, 1d, 0d, NORM_TYPE.CV_MINMAX, IntPtr.Zero);
//                //找到最匹配的点，以及该点的值
//                double bestValue;
//                Point bestPoint;
//                FindBestMatchPointAndValue(imageResult, tmType, out bestValue, out bestPoint);
//                //在最匹配的点附近画一个跟模板一样大的矩形
//                Rectangle rect = new Rectangle(new Point(bestPoint.X - imageTemplate.Size.Width / 2, bestPoint.Y - imageTemplate.Size.Height / 2), imageTemplate.Size);
//                imageResult.Draw(rect, new Gray(bestValue), 2);
//                //保存结果图像到数组
//                imageResults[i] = imageResult;
//                i++;
//                //显示结果
//                txtResult.Text += string.Format("匹配方式：{0:G}，用时：{1:F05}毫秒，最匹配的点：({2},{3})，最匹配的值：{4}/r/n", tmType, time, bestPoint.X, bestPoint.Y, bestValue);
//            }
//            txtResult.Text += string.Format("匹配结束，共用时：{0:F05}毫秒/r/n", totalTime);
//            //显示结果图像
//            pbResultSqdiff.Image = ImageConverter.ImageSingleToBitmap<Gray>(imageResults[0]);
//            pbResultSqdiffNormalized.Image = ImageConverter.ImageSingleToBitmap<Gray>(imageResults[1]);
//            pbResultCcorr.Image = ImageConverter.ImageSingleToBitmap<Gray>(imageResults[2]);
//            pbResultCcorrNormalized.Image = ImageConverter.ImageSingleToBitmap<Gray>(imageResults[3]);
//            pbResultCcoeff.Image = ImageConverter.ImageSingleToBitmap<Gray>(imageResults[4]);
//            pbResultCcoeffNormalized.Image = ImageConverter.ImageSingleToBitmap<Gray>(imageResults[5]);
//            //释放资源
//            imageInput.Dispose();
//            imageTemplate.Dispose();
//            imageInput2.Dispose();
//            imageTemplate2.Dispose();
//            foreach (Image<Gray, Single> imageResult in imageResults)
//                imageResult.Dispose();
//        }

//        //找到最匹配的点，以及该点的值
//        private void FindBestMatchPointAndValue(Image<Gray, Single> image, TM_TYPE tmType, out double bestValue, out Point bestPoint)
//        {
//            bestValue = 0d;
//            bestPoint = new Point(0, 0);
//            double[] minValues, maxValues;
//            Point[] minLocations, maxLocations;
//            image.MinMax(out minValues, out maxValues, out minLocations, out maxLocations);
//            //对于平方差匹配和归一化平方差匹配，最小值表示最好的匹配；其他情况下，最大值表示最好的匹配
//            if (tmType == TM_TYPE.CV_TM_SQDIFF || tmType == TM_TYPE.CV_TM_SQDIFF_NORMED)
//            {
//                bestValue = minValues[0];
//                bestPoint = minLocations[0];
//            }
//            else
//            {
//                bestValue = maxValues[0];
//                bestPoint = maxLocations[0];
//            }
//        }
//        /// <summary>
//        /// 将任意浮点型图像转换成Byte图像；
//        /// 本转换函数对浮点型图像的具体像素值没有要求，自动将值缩放到0～255之间。
//        /// </summary>
//        /// <typeparam name="TColor">图像的色彩空间</typeparam>
//        /// <param name="source">浮点型图像</param>
//        /// <returns>返回Byte型图像</returns>
//        public static Image<TColor, Byte> ImageSingleToByte<TColor>(Image<TColor, Single> source)
//            where TColor : struct, IColor
//        {
//            Image<TColor, Byte> dest = new Image<TColor, Byte>(source.Size);
//            //得到源图像的最小和最大值
//            double[] minVal, maxVal;
//            Point[] minLoc, maxLoc;
//            source.MinMax(out minVal, out maxVal, out minLoc, out maxLoc);
//            double min = minVal[0];
//            double max = maxVal[0];
//            for (int i = 1; i < minVal.Length; i++)
//            {
//                min = Math.Min(min, minVal[i]);
//                max = Math.Max(max, maxVal[i]);
//            }
//            //得到缩放比率和偏移量
//            double scale = 1.0, shift = 0.0;
//            scale = (max == min) ? 0.0 : 255.0 / (max - min);
//            shift = (scale == 0) ? min : -min * scale;
//            //缩放图像，并浮点图像缩放到256级的灰度
//            CvInvoke.cvConvertScaleAbs(source.Ptr, dest.Ptr, scale, shift);
//            return dest;
//        }

//        /// <summary>
//        /// 将任意浮点型图像转换成每通道8位的Bitmap；
//        /// 本转换函数对浮点型图像的具体像素值没有要求，自动将值缩放到0～255之间。
//        /// </summary>
//        /// <typeparam name="TColor">图像的色彩空间</typeparam>
//        /// <param name="source">浮点型图像</param>
//        /// <returns>返回每通道8位的Bitmap</returns>
//        public static Bitmap ImageSingleToBitmap<TColor>(Image<TColor, Single> source)
//            where TColor : struct, IColor
//        {
//            Image<TColor, Byte> dest = ImageSingleToByte<TColor>(source);
//            Bitmap bitmap = dest.Bitmap;
//            dest.Dispose();
//            return bitmap;
//        }


//    }
//}
//using System;
//using System.Collections.Generic;
//using System.ComponentModel;
//using System.Data;
//using System.Drawing;
//using System.Linq;
//using System.Text;
//using System.Windows.Forms;
//using Emgu.CV;
//using Emgu.Util;
//using Emgu.CV.Structure;
//using Emgu.CV.CvEnum;
//using System.Diagnostics;
 
//namespace Chuanlin2012._01
//{
//    public partial class MainFrm : Form
//    {
//        public Image<Bgr, byte> src;
//        public Image<Bgr, byte> subsrc;     
//        public MainFrm()
//        {
//            InitializeComponent();
//        }
 
//        private void 打开ToolStripMenuItem_Click(object sender, EventArgs e)
//        {
//            OpenFileDialog opflg = new OpenFileDialog();
//            opflg.Filter = "所有文件|*.*";
//            if (opflg.ShowDialog() == DialogResult.OK)
//            {
//                Image<Bgr, byte> rgbimg1 = new Image<Bgr, byte>(opflg.FileName);
//                imageBox1.Image = rgbimg1;
//                src = rgbimg1;
              
//            }
//        }
 
//        private void 保存ToolStripMenuItem_Click(object sender, EventArgs e)
//        {
//            if (imageBox1.Image != null)
//            {
//                SaveFileDialog sfdlg = new SaveFileDialog();
//                sfdlg.Filter = "bmp文件|*.bmp";
//                sfdlg.FilterIndex = 2;
//                sfdlg.RestoreDirectory = true;
//                if (sfdlg.ShowDialog() == DialogResult.OK)
//                {
//                    string fname = sfdlg.FileName;
//                    Bitmap bmp = imageBox1.Image.Bitmap;
//                    bmp.Save(fname, System.Drawing.Imaging.ImageFormat.Bmp);
//                }
//            }
//            else
//            {
//                System.Windows.Forms.MessageBox.Show("请先打开图像！");
//                return;
//            }
 

//        }
 
//   private void 退出ToolStripMenuItem_Click_1(object sender, EventArgs e)
//        {
//            this.Close();
//        }
 
//        private void sobel算子ToolStripMenuItem_Click(object sender, EventArgs e)
//        {
//            if (imageBox1.Image != null)
//            {
//                Image<Bgr, float> imgsoble = src.Sobel(0, 1, 3);
//                imageBox1.Image = imgsoble;
//            }
//            else
//            {
//                System.Windows.Forms.MessageBox.Show("请先打开图像！");
//                return;
//            }
                
//        }
 
//                private void laplace算子ToolStripMenuItem_Click(object sender, EventArgs e)
//        {
//            if (imageBox1.Image != null)
//            {
//                Image<Bgr, float> imglaplace = src.Laplace(3);
//                imageBox1.Image = imglaplace;
//            }
//            else 
//            {
//                System.Windows.Forms.MessageBox.Show("请先打开图像！");
//                return;
//            }
//        }

//             private void canny算子ToolStripMenuItem_Click(object sender, EventArgs e)
//        {
//            if (imageBox1.Image != null)
//            {
//                //CannyFrm cfrm = new CannyFrm();
//                //cfrm.Show();
//                double m = 90;
//                double n = 255;
//                Gray threshold1 = new Gray(m);
//                Gray threshold2 = new Gray(n);
//                Image<Gray, byte> imggray = src.Convert<Gray, byte>();
//                Image<Gray, byte> imgcanny = imggray.Canny(threshold1, threshold2);
                
//                imageBox1.Image = imgcanny;
               
//            }
//            else
//                System.Windows.Forms.MessageBox.Show("请先输入图像！");
//        }
 
//        private void 二值化后绘制图像轮廓ToolStripMenuItem_Click(object sender, EventArgs e)
//        {
//            if (imageBox1.Image != null)
//            {
//                Image<Gray, byte> imggray = src.Convert<Gray, byte>();
//                Image<Gray, byte> img2b = imggray.ThresholdBinary(new Gray(60), new Gray(255));
//                Contour<Point> contour = img2b.FindContours();        //找轮廓
//                Image<Bgr, byte> imgbgr = img2b.Convert<Bgr, byte>();
//                int maxLevel = 0;                                                           //绘制的轮廓深度
//                imgbgr.Draw(contour, new Bgr(0, 0, 255), new Bgr(0, 0, 255), maxLevel, 1);//绘制图像轮廓
//                imageBox1.Image = imgbgr;                            
//            }
//            else
//                System.Windows.Forms.MessageBox.Show("请先输入图像！");
//        }
 
 
//        private void SmoothBlur算子ToolStripMenuItem_Click(object sender, EventArgs e)
//        {
//            if (imageBox1.Image != null)
//            {
//                Image<Bgr, byte> imgsmoot = src.SmoothBlur(9, 9);
//                imageBox1.Image = imgsmoot;
 
//            }
//        }
 
//        private void button1_Click(object sender, EventArgs e)
//        {
//            OpenFileDialog opdlg = new OpenFileDialog();
//            opdlg.Filter = "所有文件|*.*";
//            if (opdlg.ShowDialog() == DialogResult.OK)
//            {
//                Image<Bgr, byte> imgrgb = new Image<Bgr, byte>(opdlg.FileName);
//                imageBox2.Image = imgrgb;
//                subsrc = imgrgb;
//            }
//        }
 
////六种模板匹配方法
//        private void radioButton1_CheckedChanged(object sender, EventArgs e)
//        {
//            if (imageBox1.Image != null && imageBox2.Image != null)
//            {
//                double time;
//                double totalTime = 0;
//                Stopwatch sw = new Stopwatch();
//                sw.Start();
 
//                //输入图像            
//                Image<Bgr, Byte> imageInput =src ;
//                //模板图像            
//                Image<Bgr, Byte> imageTemplate = subsrc;
              
//                //匹配方式数组
//                TM_TYPE tmType = TM_TYPE.CV_TM_CCOEFF;
//                //输出图像（匹配结果）
//                Image<Gray, Single> imageResult = imageInput.MatchTemplate(imageTemplate,tmType);             
//                //归一化结果               
//                //CvInvoke.cvNormalize(imageResult.Ptr, imageResult.Ptr, 1d, 0d, NORM_TYPE.CV_MINMAX, IntPtr.Zero);
//                //imageBox1.Image = imageResult;
                
//                //找到最匹配的点，以及该点的值                
//                double bestValue;                
//                Point bestPoint;                
//                FindBestMatchPointAndValue(imageResult, tmType, out bestValue, out bestPoint);
//                //在最匹配的点附近画一个跟模板一样大的矩形                
//                Rectangle rect = new Rectangle(new Point(bestPoint.X - imageTemplate.Size.Width / 2, bestPoint.Y - imageTemplate.Size.Height / 2), imageTemplate.Size);               
//                imageResult.Draw(rect, new Gray(bestValue), 2);
//                imageBox1.Image = imageResult;               
//                time = sw.Elapsed.TotalMilliseconds; 
//                totalTime += time;
//                sw.Stop();
//                textBox1.Text = totalTime.ToString();
//                sw.Reset();
         
//            }
//            else
//                System.Windows.Forms.MessageBox.Show("请先输入图像！");
//        }
      
//         private void radioButton2_CheckedChanged(object sender, EventArgs e)
//         {
//             if (imageBox1.Image != null && imageBox2.Image != null)
//             {
//                 //输入图像            
//                 Image<Bgr, Byte> imageInput = src;
//                 //模板图像            
//                 Image<Bgr, Byte> imageTemplate = subsrc;
//                 TM_TYPE tmtype = TM_TYPE.CV_TM_CCORR;
//                 Image<Gray, Single> imgResult = imageInput.MatchTemplate(imageTemplate, tmtype);
//                 //找到最好的点和最好点的值
//                 double bestValue;
//                 Point bestPoint;
//                 FindBestMatchPointAndValue(imgResult,tmtype,out  bestValue,out  bestPoint);
//                 Rectangle rect = new Rectangle(new Point(bestPoint.X - imageTemplate.Width / 2, bestPoint.Y - imageTemplate.Height / 2), imageTemplate.Size);
//                 imgResult.Draw(rect, new Gray(bestValue), 2);
//                 imageBox1.Image = imgResult;
//             }
//             else
//             {
//                 System.Windows.Forms.MessageBox.Show("请先输入图像！");
//             }
//         }
 
//         private void radioButton3_CheckedChanged(object sender, EventArgs e)
//         {
//               if(imageBox1.Image!=null && imageBox2.Image!=null)
//               {
//                   //输入图像            
//                 Image<Bgr, Byte> imageInput = src;
//                 //模板图像            
//                 Image<Bgr, Byte> imageTemplate = subsrc;
//                 TM_TYPE tmtype = TM_TYPE.CV_TM_SQDIFF;
//                 Image<Gray, Single> imgResult = imageInput.MatchTemplate(imageTemplate, tmtype);
//                 //找到最好的点和最好点的值
//                 double bestValue;
//                 Point bestPoint;
//                 FindBestMatchPointAndValue(imgResult,tmtype,out  bestValue,out  bestPoint);
//                 Rectangle rect = new Rectangle(new Point(bestPoint.X - imageTemplate.Width / 2, bestPoint.Y - imageTemplate.Height / 2), imageTemplate.Size);
//                 imgResult.Draw(rect, new Gray(bestValue), 2);
//                 imageBox1.Image = imgResult;
            
//             }
//             else
//             {
//                 System.Windows.Forms.MessageBox.Show("请先输入图像！");
//             }
//         }
 
//         private void radioButton4_CheckedChanged(object sender, EventArgs e)
//         {
//             if (imageBox1.Image != null && imageBox2.Image != null)
//             {
//                 //输入图像            
//                 Image<Bgr, Byte> imageInput = src;
//                 //模板图像            
//                 Image<Bgr, Byte> imageTemplate = subsrc;
//                 TM_TYPE tmtype = TM_TYPE.CV_TM_CCOEFF_NORMED;
//                 Image<Gray, Single> imgResult = imageInput.MatchTemplate(imageTemplate, tmtype);
//                 //找到最好的点和最好点的值
//                 double bestValue;
//                 Point bestPoint;
//                 FindBestMatchPointAndValue(imgResult, tmtype, out  bestValue, out  bestPoint);
//                 Rectangle rect = new Rectangle(new Point(bestPoint.X - imageTemplate.Width / 2, bestPoint.Y - imageTemplate.Height / 2), imageTemplate.Size);
//                 imgResult.Draw(rect, new Gray(bestValue), 2);
//                 imageBox1.Image = imgResult;
                
//             }
//             else
//             {
//                 System.Windows.Forms.MessageBox.Show("请先输入图像！");
//             }
//         }
 
//         private void radioButton5_CheckedChanged(object sender, EventArgs e)
//         {
//             if (imageBox1.Image != null && imageBox2.Image != null)
//             {
//                 //输入图像            
//                 Image<Bgr, Byte> imageInput = src;
//                 //模板图像            
//                 Image<Bgr, Byte> imageTemplate = subsrc;
//                 TM_TYPE tmtype = TM_TYPE.CV_TM_CCORR_NORMED;
//                 Image<Gray, Single> imgResult = imageInput.MatchTemplate(imageTemplate, tmtype);
//                 //找到最好的点和最好点的值
//                 double bestValue;
//                 Point bestPoint;
//                 FindBestMatchPointAndValue(imgResult, tmtype, out  bestValue, out  bestPoint);
//                 Rectangle rect = new Rectangle(new Point(bestPoint.X - imageTemplate.Width / 2, bestPoint.Y - imageTemplate.Height / 2), imageTemplate.Size);
//                 imgResult.Draw(rect, new Gray(bestValue), 2);
//                 imageBox1.Image = imgResult;
//             }
//             else
//             {
//                 System.Windows.Forms.MessageBox.Show("请先输入图像！");
//             }
//         }
//         private void radioButton6_CheckedChanged(object sender, EventArgs e)
//         {
//             if (imageBox1.Image != null && imageBox2.Image != null)
//             {
//                 //输入图像            
//                 Image<Bgr, Byte> imageInput = src;
//                 //模板图像            
//                 Image<Bgr, Byte> imageTemplate = subsrc;
//                 TM_TYPE tmtype = TM_TYPE.CV_TM_SQDIFF_NORMED;
//                 Image<Gray, Single> imgResult = imageInput.MatchTemplate(imageTemplate, tmtype);
//                 //找到最好的点和最好点的值
//                 double bestValue;
//                 Point bestPoint;
//                 FindBestMatchPointAndValue(imgResult, tmtype, out  bestValue, out  bestPoint);
//                 Rectangle rect = new Rectangle(new Point(bestPoint.X - imageTemplate.Width / 2, bestPoint.Y - imageTemplate.Height / 2), imageTemplate.Size);
//                 imgResult.Draw(rect, new Gray(bestValue), 2);
                
//             }
//             else
//             {
//                 System.Windows.Forms.MessageBox.Show("请先输入图像！");
//             }
//         }
//         private void FindBestMatchPointAndValue(Image<Gray, Single> image, TM_TYPE tmType, out double bestValue, out Point bestPoint)
//         {
//             bestValue = 0d;
//             bestPoint = new Point(0, 0);
//             double[] minValues, maxValues;
//             Point[] minLocations, maxLocations;
//             image.MinMax(out minValues, out maxValues, out minLocations, out maxLocations);
//             //对于平方差匹配和归一化平方差匹配，最小值表示最好的匹配；其他情况下，最大值表示最好的匹配            
//             if (tmType == TM_TYPE.CV_TM_SQDIFF || tmType == TM_TYPE.CV_TM_SQDIFF_NORMED)
//             {
//                 bestValue = minValues[0];
//                 bestPoint = minLocations[0];
//             }
//             else
//             {
//                 bestValue = maxValues[0];
//                 bestPoint = maxLocations[0];
//             }
//         }
//         private void 图像对比ToolStripMenuItem_Click(object sender, EventArgs e)
//         {
//             CompareFrm cpfrm = new CompareFrm();
//             cpfrm.Show();
//         }

     
//    }
//}
